﻿using System;
using System.Web.Mvc;
using DiNinject.Web.UI.Models.Person;
using DiNinject.Web.UI.Models.Person.ModelBuilderInterfaces;

namespace DiNinject.Web.UI.Controllers
{
    public class PersonController : Controller
    {
        #region Initialize
        public PersonController(IPersonModelBuilder personModelBuilder)
        {
            if (personModelBuilder == null)
            {
                throw new NullReferenceException("PersonModelBuilder ist Null.");
            }

            _personModelBuilder = personModelBuilder;
        }

        private IPersonModelBuilder _personModelBuilder;
        #endregion

        #region Views
        /// <summary>
        /// Model mit einem leeren PersonenModel anlegen
        /// </summary>
        public ActionResult AddPerson()
        {   
           return View(_personModelBuilder.Load());
        }
        
        /// <summary>
        /// Erstellen einer neuen Person
        /// </summary>
        [HttpPost]
        public ActionResult AddPerson(PersonEditModel editModel)
        {
            if (ModelState.IsValid)
            {
                _personModelBuilder.AddOrSavePerson(editModel);
                return RedirectToAction("PersonList");
            }

            return View(editModel);
        }

        /// <summary>
        /// Bearbeiten einer einzelnen Person mit der übergebenen Id
        /// </summary>
        public ActionResult EditPerson(int id)
        {
            return View(_personModelBuilder.Load(id));
        }

        /// <summary>
        /// Speichern der Personendaten die übergeben wurden im Post
        /// </summary>
        [HttpPost]
        public ActionResult EditPerson(PersonEditModel editModel)
        {
            if (ModelState.IsValid)
            {
                _personModelBuilder.AddOrSavePerson(editModel);
                return RedirectToAction("Person", "Person", new {id = editModel.Id});
            }

            return View(editModel);
        }

        /// <summary>
        /// Anzeigen der Details einer einzelnen Person
        /// </summary>
        public ActionResult Person(int id)
        {
            return View(_personModelBuilder.Load(id));
        }

        /// <summary>
        /// Laden aller Personen 
        /// </summary>
        public ActionResult PersonList()
        {
            return View();
        }
        #endregion 
    }
}